package ylg.com.cn.youtube.main;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import ylg.com.cn.youtube.R;
import ylg.com.cn.youtube._commons.customviews.YoutubeLayout;
import ylg.com.cn.youtube._data.Video;
import ylg.com.cn.youtube._data.source.remote.UserRemoteDataSource;
import ylg.com.cn.youtube._data.source.remote.VideoRemoteDataSource;
import ylg.com.cn.youtube.main.fragment_home.HomePageContract;
import ylg.com.cn.youtube.main.fragment_home.HomePageFragment;
import ylg.com.cn.youtube.main.fragment_home.HomePagePresenter;
import ylg.com.cn.youtube.main.fragment_hot.HotPageFragment;
import ylg.com.cn.youtube.main.fragment_user.UserPageContract;
import ylg.com.cn.youtube.main.fragment_user.UserPageFragment;
import ylg.com.cn.youtube.main.fragment_user.UserPagePresenter;

public class MainActivity extends AppCompatActivity implements HomePageFragment.OnFragmentInteractionListener,HotPageFragment.OnFragmentInteractionListener,UserPageFragment.OnFragmentInteractionListener{
    public static final long DURATION = 300;
    /* 内部所有fragment的presenter */
    public HomePagePresenter homePagePresenter;
    public UserPagePresenter userPagePresenter;

    // models
    public UserRemoteDataSource userremote;
    private VideoRemoteDataSource homePageRemote;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initActionBar();
        initViewPager();
        initRemote();

    }

    ViewPager vp;
    TabLayout tabs;
    AppBarLayout appbar;
    Toolbar toolbar;
    // YoutubeLayout
    YoutubeLayout ytb;
    private void initViews(){
        vp = (ViewPager) findViewById(R.id.vpcontainer);
        tabs = (TabLayout) findViewById(R.id.tabs);
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        ytb = (YoutubeLayout) findViewById(R.id.youtubelayout);
    }
    private void initActionBar(){
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getString(R.string.home_tab));
        setSupportActionBar(toolbar);
    }

    private MainActivityPageAdapter adapter;


    private void initViewPager(){
        adapter = new MainActivityPageAdapter(getSupportFragmentManager());
        vp.setOffscreenPageLimit(2);
        vp.setAdapter(adapter);
        tabs.setupWithViewPager(vp);
        int[] sFocusedSelected = {
                android.R.attr.state_selected
        };
        int[] sDefaultSelected = {};

        // 默认 -- 白色 图标
        Drawable dhome = ContextCompat.getDrawable(this, R.mipmap.ic_tab_home);
        Drawable dhot = ContextCompat.getDrawable(this, R.mipmap.ic_tab_trending);
        Drawable daccount = ContextCompat.getDrawable(this, R.mipmap.ic_tab_account);

        //  被改色的图标
        Drawable dhome_dark = filter(R.mipmap.ic_tab_home);
        Drawable dhot_dark = filter(R.mipmap.ic_tab_trending);
        Drawable daccount_dark = filter(R.mipmap.ic_tab_account);

        // 创建selector
        StateListDrawable sdhome = new StateListDrawable();
        sdhome.addState(sFocusedSelected, dhome);
        sdhome.addState(sDefaultSelected, dhome_dark);

        StateListDrawable sdhot = new StateListDrawable();
        sdhot.addState(sFocusedSelected, dhot);
        sdhot.addState(sDefaultSelected, dhot_dark);

        StateListDrawable sdacc = new StateListDrawable();
        sdacc.addState(sFocusedSelected, daccount);
        sdacc.addState(sDefaultSelected, daccount_dark);

        ImageView ihm = new ImageView(this);
        ihm.setImageDrawable(sdhome);
        ImageView iht = new ImageView(this);
        iht.setImageDrawable(sdhot);
        ImageView iacc = new ImageView(this);
        iacc.setImageDrawable(sdacc);

        int padding = getResources().getDimensionPixelSize(R.dimen.tab_padding);
        // 有于本view还没加入改布局的原因， 可以通过本方法添加padding
        ViewCompat.setPaddingRelative(ihm, padding, padding, padding, padding);
        ViewCompat.setPaddingRelative(iht, padding, padding, padding, padding);
        ViewCompat.setPaddingRelative(iacc, padding, padding, padding, padding);

        //
        tabs.getTabAt(0).setCustomView(ihm);
        tabs.getTabAt(1).setCustomView(iht);
        tabs.getTabAt(2).setCustomView(iacc);


        // 更改tab 下线的颜色
        ihm.setSelected(true);
        tabs.setSelectedTabIndicatorColor(Color.WHITE);
        tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 切换activity 标题
                toolbar.setTitle(adapter.getPageTitle(tab.getPosition()));

                // 绑定viewpager和当前点击的tab
                vp.setCurrentItem(tab.getPosition());

                // 之后再第一次切换到本fragment 的时候才会开始加载数据
                if (tab.getPosition() == 1) {
                    ((HotPageFragment)frg.get(1).get()).setToLoad();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                appbar.setExpanded(true, true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initRemote() {
        userremote = new UserRemoteDataSource(this);
       homePageRemote = new VideoRemoteDataSource(this);
    }

    private boolean isFirst = false;
    @Override
    public void playVideo(Video video, View v) {
        if (ytb != null && ytb.getVisibility() != View.VISIBLE) {
            ytb.setVisibility(View.VISIBLE);
            ytb.requestHeaderContent();
        }
        ytb.setVideo(null, isFirst);
    }

    Map<Integer, WeakReference<Fragment>> frg;

    class MainActivityPageAdapter extends FragmentPagerAdapter {

        public MainActivityPageAdapter(FragmentManager fm) {
            super(fm);
        }

        /* 返回fragment方法 */
        @Override
        public Fragment getItem(int position) {

            if (frg == null) {
                frg = new HashMap<>();
            }
            switch (position) {
                case 0:
                    //
                    if (frg.get(0) == null) {
                        Fragment f0 = HomePageFragment.newInstance();
                        frg.put(position, new WeakReference<Fragment>(f0));
                        homePagePresenter = new HomePagePresenter((HomePageContract.View) frg.get(position).get(), homePageRemote);
                        ((HomePageContract.View) ( frg.get(position).get())).setPresenter(homePagePresenter);
                    }
                    break;
                case 1:
                    //
                    if (frg.get(position) == null) {
                        Fragment f0 = HotPageFragment.newInstance();
                        frg.put(position, new WeakReference<Fragment>(f0));
                    }
                    break;
                case 2:
                    //
                    if (frg.get(position) == null) {
                        Fragment f0 = UserPageFragment.newInstance();
                        frg.put(position, new WeakReference<Fragment>(f0));
                        userPagePresenter = new UserPagePresenter((UserPageContract.View) frg.get(position).get(), userremote);
                        ((UserPageContract.View) ( frg.get(position).get())).setPresenter(userPagePresenter);
                    }
                    break;
            };
            return frg.get(position).get();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            //
            String title = "";
            switch (position){
                case 0:
                    title = getString(R.string.home_tab);
                    break;
                case 1:
                    title = getString(R.string.hot_tab);
                    break;
                case 2:
                    title = getString(R.string.user_tab);
                    break;
            }
            return title;
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    public Drawable filter(int drawableId) {
        int iColor = Color.parseColor("#FF5E1E1C");
        return new ColouredDrawable(BitmapFactory.decodeResource(getResources(),
                drawableId),
                iColor,
                getResources());

    }

    /* 通过bitmap创建drawable：
    * 主要原理就是：
    *   1- 创建画板
    *   2- 给画板添加颜色过滤器，颜色过滤器作用就是把画板上的颜色都处理。我们这只需要把板上的颜色
    *       都改成黑色。
    * */
    public class ColouredDrawable extends BitmapDrawable {

        private ColorFilter mColorFilter;

        public ColouredDrawable(Bitmap toTransform, int toColour, Resources resources) {
            super(resources, toTransform);
            float[] matrix = {
                    0, 0, 0, 0, ((toColour & 0xFF0000) / 0xFFFF),
                    0, 0, 0, 0, ((toColour & 0xFF00) / 0xFF),
                    0, 0, 0, 0, (toColour & 0xFF),
                    0, 0, 0, 1, 0};
            mColorFilter = new ColorMatrixColorFilter(matrix);
        }

        @Override
        public void draw(Canvas canvas) {
            // 给canvas （画板） 添加过滤器
            setColorFilter(mColorFilter);
            super.draw(canvas);
        }
    }
}
